import { Button, Image, Input, View } from "@tarojs/components";
import clsx from "clsx";
import { useState } from "react";
import goubox from "@/as/btn_check_box_2.png";

interface Pay1 {
  month: number; //月份
  emi: number; //还款额
  principal: number; //本金
  interest: number; //利息
  remainingPrincipal: number; //剩余本金
}

function calculateEMI(
  principal: number,
  annualInterestRate: number,
  numberOfPayments: number
) {
  const monthlyInterestRate = annualInterestRate / 12 / 100;
  const emi =
    (principal *
      (monthlyInterestRate *
        Math.pow(1 + monthlyInterestRate, numberOfPayments))) /
    (Math.pow(1 + monthlyInterestRate, numberOfPayments) - 1);

  const results: Pay1[] = [];

  for (let month = 1; month <= numberOfPayments; month++) {
    const currentMonthInterest = principal * monthlyInterestRate;
    const currentMonthPrincipal = emi - currentMonthInterest;
    principal -= currentMonthPrincipal;
    results.push({
      month,
      emi: parseFloat(emi.toFixed(2)),
      principal: parseFloat(currentMonthPrincipal.toFixed(2)),
      interest: parseFloat(currentMonthInterest.toFixed(2)),
      remainingPrincipal: parseFloat(principal.toFixed(2)),
    });
  }

  return results;
}

function calculateEqualPrincipal(
  principal: number,
  annualInterestRate: number,
  numberOfPayments: number
) {
  const monthlyInterestRate = annualInterestRate / 12 / 100;
  const monthlyPrincipal = principal / numberOfPayments;
  const payments: Pay1[] = [];

  for (let month = 1; month <= numberOfPayments; month++) {
    const remainingPrincipal = principal - monthlyPrincipal * (month - 1);
    const interest =
      (principal - monthlyPrincipal * (month - 1)) * monthlyInterestRate;
    const emi = parseFloat((monthlyPrincipal + interest).toFixed(2));

    const payment = {
      month: month,
      principal: parseFloat(monthlyPrincipal.toFixed(2)),
      interest: parseFloat(interest.toFixed(2)),
      emi,
      remainingPrincipal: parseFloat(remainingPrincipal.toFixed(2)),
    };
    payments.push(payment);
  }

  return payments;
}

const tts = [
  {
    label: "等额本息",
    value: "principal",
  },
  { label: "等额本金", value: "interest" },
];

export default function Index() {
  const [principal, setPrincipal] = useState("100000");
  const [rate, setRate] = useState("3.1");
  const [periods, setPeriods] = useState("120");
  const [type, setType] = useState("principal");
  const [result, setResult] = useState<Pay1[]>();

  const onFilish = () => {
    if (!principal || !rate || !periods) return;

    if (type === "principal") {
      setResult(
        calculateEMI(parseFloat(principal), parseFloat(rate), parseInt(periods))
      );
    }

    if (type === "interest") {
      setResult(
        calculateEqualPrincipal(
          parseFloat(principal),
          parseFloat(rate),
          parseInt(periods)
        )
      );
    }
  };

  return (
    <>
      <View className="font-semibold text-lg sticky top-0 bg-white p-4 z-10">
        贷款计算器
      </View>
      <View className="px-4">
        <View className="flex items-center border-gray-400 border-b">
          贷款本金
          <Input
            className="flex-1 p-1"
            value={principal}
            onInput={(e) => {
              let { value } = e.detail;
              if (value.match(/^\d*(\.\d*)?$/)) {
                setPrincipal(value);
              }
            }}
          />
        </View>
        <View className="flex items-center border-gray-400 border-b">
          年利率
          <Input
            className="flex-1 p-1"
            value={rate}
            onInput={(e) => {
              let { value } = e.detail;
              if (value.match(/^\d*(\.\d*)?$/)) {
                setRate(value);
              }
            }}
          />
        </View>
        <View className="flex items-center border-gray-400 border-b">
          还款期数
          <Input
            className="flex-1 p-1"
            value={periods}
            onInput={(e) => {
              let { value } = e.detail;
              if (value.match(/^\d*$/)) {
                setPeriods(value);
              }
            }}
          />
        </View>
        <View className="p-4 grid grid-cols-2 gap-2">
          {tts.map((v, k) => (
            <View
              key={k}
              className={clsx(
                "border flex items-center justify-center",
                "p-2 rounded-md border-gray-200"
              )}
              onClick={() => setType(v.value)}
            >
              {v.label}
              {type === v.value && (
                <Image src={goubox} className="w-4 h-4 ml-2" />
              )}
            </View>
          ))}
        </View>
        <Button className="mt-2" onClick={onFilish}>
          计算
        </Button>
        {result && result.length > 0 && (
          <View className="flex border-b border-gray-600 py-1 mt-2">
            <View className="w-10">期数</View>
            <View className="w-20">还款额</View>
            <View className="w-20">还本</View>
            <View className="w-20">还息</View>
            <View className="flex-1">剩余本金</View>
          </View>
        )}
        {result?.map((d, k) => (
          <View
            key={k}
            className={clsx("flex py-1", {
              "border-b border-gray-400": k < result.length - 1,
            })}
          >
            <View className="w-10">{d.month}</View>
            <View className="w-20">{d.emi}</View>
            <View className="w-20">{d.principal}</View>
            <View className="w-20">{d.interest}</View>
            <View className="flex-1 text-right">{d.remainingPrincipal}</View>
          </View>
        ))}
      </View>
    </>
  );
}
